package com.ibm.iisp.common.datasource;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizers;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {
    @Bean
    public DataSourceTransactionManager transactionManager(DataSource dataSource,
            ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
        DataSourceTransactionManager transactionManager = new DynaDataSourceTransactionManager(dataSource);
        transactionManagerCustomizers.ifAvailable((customizers) -> customizers.customize(transactionManager));
        return transactionManager;
    }

    @ConfigurationProperties(prefix = "spring.datasources")
    @Bean(name = "dsConfig")
    public Map<String, HikariDataSource> hdfsConfig() {
        return new HashMap<>();
    }

    @Bean
    public DataSource createDataSource(@Qualifier("dsConfig") Map<String, HikariDataSource> confMap) {
        DynamicDataSource dds = new DynamicDataSource();

        for (Map.Entry<String, HikariDataSource> ent : confMap.entrySet()) {
            DataSource ds = ent.getValue();
            if ("master".equals(ent.getKey())) {
                dds.setMaster(ds);
            } else {
                dds.getSlaves().add(ds);
            }
        }
        return dds;
    }
}
